package com.wsd.common.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wsd.common.entity.UserEntity;
import com.wsd.common.entity.UserRedisEntity;
import com.wsd.common.entity.UserTokenEntity;
import com.wsd.common.mapper.UserMapper;
import com.wsd.common.utils.DateUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.NoSuchElementException;
import java.util.Objects;

@Service
public class LoginService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate<String, UserRedisEntity> redisTemplate;

    @Resource
    private UserMapper userMapper;


    /**
     * 检测redis中是否包括用户, 如果包含则用户以及登录过本系统, 如果不包含, 则提示用户授权注册
     * @param userToken 用户令牌
     * @return true or false
     */
    public UserRedisEntity containsUser(UserTokenEntity userToken) {
        UserRedisEntity userRedisEntity = null;
        userRedisEntity = redisTemplate.opsForValue().get(userToken.getOpenId());  // 暂时使用openID作为用户唯一标识
        if (Objects.isNull(userRedisEntity)) {  // 如果Redis中不存在，则到数据库中查找
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("open_id", userToken.getOpenId());
            userRedisEntity = userMapper.selectOne(queryWrapper);
            if (!Objects.isNull(userRedisEntity)) {  // 如果数据库中存在该用户，将用户信息保存到redis
                redisTemplate.opsForValue().set(userRedisEntity.getOpenId(), userRedisEntity);
            }
        }
        return userRedisEntity;
    }

    // 事务注解, 当方法catch异常时, 注解会失效
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(UserEntity userEntity) throws Exception {

        if (Objects.isNull(userEntity) || Objects.isNull(userEntity.getOpenId())) {
            throw new NoSuchElementException();
        }

        // 将用户信息保存到数据库
        String nowStr = DateUtils.currentDateNString();
        userEntity.setLoginTime(nowStr);
        userEntity.setUpdateTime(nowStr);
        userEntity.setCreateTime(nowStr);

        userMapper.insert(userEntity);

        // 将用户数据保存到redis中
        redisTemplate.opsForValue().setIfAbsent(userEntity.getOpenId(), userEntity);
    }


    /**
     * 更新最近登录
     * @param userEntity entity
     */
    public void updateLoginStatus(UserEntity userEntity) {
        UpdateWrapper<UserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("login_time", DateUtils.currentDateNString());
        updateWrapper.set("login_ip", userEntity.getLoginIp());
        updateWrapper.eq("open_id", userEntity.getOpenId());
        userMapper.update(null, updateWrapper);
    }

}
